package dynamic_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Administrator on 2019/10/25.
 */
public class DP
{
    public static void main(String[] args){

        People p = (People) Proxy.newProxyInstance(People.class.getClassLoader(), new Class[]{People.class}, new Handler(new GreenPeople()));
        p.eat();
        Book b = (Book)Proxy.newProxyInstance(Book.class.getClassLoader(), new Class[]{Book.class}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
            {
                System.out.println(method.toString() + args[0]);
                return null;
            }
        });
        b.sell("aa");
    }

    static class Handler implements InvocationHandler{
        People p;

        public Handler(People p)
        {
            this.p = p;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        {
            System.out.println("执行之前");
            Object obj = method.invoke(p, args);
            System.out.println("执行之后");
            return obj;
        }
    }

    interface Book{
        void sell(String ss);
    }

    interface People{
        void eat();
        void sleep();
    }

    static class GreenPeople implements People{

        @Override
        public void eat()
        {
            System.out.println("green people eat");
        }

        @Override
        public void sleep()
        {
            System.out.println("green people sleep");
        }
    }
}
